/*
 * main.cpp
 *
 *  Created on: 2013. 1. 31.
 *      Author: jjaehuny
 */

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <Dispatcher/Static.h>

#include "src/ListenHandler.h"
#include "src/ChannelServer.h"

#include "idl/Cache.h"

#include "src/User.h"

#include <vector>
#include <string>

#include "src/Static.h"

struct Temp
{
public:
	UserInfo & GetUserInfo() { return _stUserInfo; }
	void SetUserInfo( UserInfo & userInfo) { _stUserInfo = userInfo; }
private:
	UserInfo _stUserInfo;
};

struct Value
{
public:
	UserInfo &		GetUserInfo() { return _userInfo; }
	void 			SetUserInfo(UserInfo userInfo) { _userInfo = userInfo; }

	UserInfo 			_userInfo;
};

int main(int argc, char **argv) {

	std::mutex mutex_;
	std::condition_variable condition_;

	if(false == Logger::Init())
	{
		return 0;
	}

	Logger::SetLevelProperty(Logger::LOG_LEVEL_DEV, Logger::LOG_STDERR|Logger::LOG_FILE);
	Logger::SetLevelProperty(Logger::LOG_LEVEL_INF, Logger::LOG_STDERR|Logger::LOG_FILE);
	Logger::SetLevelProperty(Logger::LOG_LEVEL_ERR, Logger::LOG_STDERR|Logger::LOG_FILE|Logger::LOG_SYSLOG);

	boost::property_tree::ptree ptree_;
	try
	{
		boost::property_tree::xml_parser::read_xml("./conf/CacheServer.xml", ptree_);
	}
	catch (boost::exception& e)
	{
		LOG(ERR, "fail to read config(./conf/CacheServer.xml)");
		return 0;
	}

	LOG(INF, "========== CACHE SERVER Server Start ==========");
	LOG(INF, "boost ver : ", BOOST_LIB_VERSION);
	LOG(INF, "build ver : ", __DATE__, " ", __TIME__);

	if(false == Dispatcher::Init())
	{
		LOG(ERR, "fail to init Dispatcher lib");
		return 0;
	}

	int listenPort = ptree_.get<int>("server.session.<xmlattr>.port");
	LOG(INF, "listen port : ", listenPort);
	std::shared_ptr< ::CacheServer::ListenHandler> pListenHandler(new ::CacheServer::ListenHandler());
	if(false == Dispatcher::Listen(listenPort, pListenHandler.get(), 1024))
	{
		LOG(ERR, "fail to listen(port:", listenPort, ")");
		return false;
	}


	if(false == Database::Init())
	{
		return 0;
	}

	const char * host =  ptree_.get<std::string>("server.database.connection.<xmlattr>.host").c_str();
	const char * id = ptree_.get<std::string>("server.database.connection.<xmlattr>.user").c_str();
	const char * pass = ptree_.get<std::string>("server.database.connection.<xmlattr>.passwd").c_str();
	const char * schema = ptree_.get<std::string>("server.database.connection.<xmlattr>.db").c_str();

	if(false == Database::Connect(1, host, 3306, id, pass, schema))
	{
		std::cerr << "DB Connect Error" << std::endl;
		return 0;
	}

	::CacheServer::Static clsStatic;
	srand((unsigned)time(NULL));

	LOG(INF, "[CACHE SERVER START]");

	std::unique_lock<std::mutex> lock(mutex_);
	condition_.wait(lock);
	return 0;
}

